﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla.Rules;

namespace Validation
{
    public class UniqueValidation : ValidationBase
    {
        public string TableName { get; set; }
        public string FieldName { get; set; }
        public string FieldType { get; set; }

        public UniqueValidation(Csla.Core.IPropertyInfo PrimaryProperty, string ValidationMessage, string TableName, string FieldName, string FieldType)
            : base(PrimaryProperty, ValidationMessage)
        {
            IsAsync = true;
            ProvideTargetWhenAsync = true;
            this.TableName = TableName;
            this.FieldName = FieldName;
            this.FieldType = FieldType;
            InputProperties = new List<Csla.Core.IPropertyInfo> { PrimaryProperty };
        }

        protected override void Execute(RuleContext context)
        {
            string primaryValue = context.InputPropertyValues[PrimaryProperty].ToString();
            if (primaryValue != "")
            {
                CheckExistService.CheckExist(TableName, FieldName, FieldType, primaryValue, (o, ex) =>
                {
                    if (ex.Error == null)
                    {
                        CheckExistService service = ex.Object;
                        if (service.IsExist)
                        {
                            context.AddErrorResult(this.ValidationMessage);
                        }
                    }
                    context.Complete();
                });
            }
        }
    }
}
